package com.xs.tool.common.lambda;

import com.alibaba.fastjson.JSON;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @author 孙泽权
 * @email 1226112135@qq.com
 * @date 2021/4/16 上午12:24
 * https://blog.csdn.net/qq496013218/article/details/76651760
 * @description https://www.jianshu.com/p/2344f381c643?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation
 */
public class DemoLambda {
    private static DemoLambda instance = null;

    // 双重检查
    public static DemoLambda getInstance() {
        if (instance == null) {
            synchronized (DemoLambda.class) {
                if (instance == null) {
                    instance = new DemoLambda();
                }
            }
        }
        return instance;
    }

    /**
     * 流的构造与转换
     * 下面提供最常见的几种构造 Stream 的样例
     */
    public void stream() {
        // 1. Individual values
        Stream stream = Stream.of("a", "b", "c");
        // 2. Arrays
        String[] strArray = new String[]{"a", "b", "c"};
        stream = Stream.of(strArray);
        stream = Arrays.stream(strArray);
        // 3. Collections
        List<String> list = Arrays.asList(strArray);
        stream = list.stream();

        System.out.println("清单 5. 数值流的构造");
        IntStream.of(new int[]{1, 2, 3}).forEach(System.out::println);
        System.out.println("------------");
        IntStream.range(1, 3).forEach(System.out::println);
        System.out.println("------------");
        IntStream.rangeClosed(1, 3).forEach(System.out::println);
        System.out.println("------------");
        System.out.println("清单 6. 流转换为其它数据结构");
        // 1. Array
        Object[] strArray1 = stream.toArray(String[]::new);
        // 2. Collection
        List<String> nums = Arrays.asList("1", "2", "3", "4");
        List<String> list1 = nums.stream().collect(Collectors.toList());
        List<String> list2 = nums.stream().collect(Collectors.toCollection(ArrayList::new));
        Set set1 = nums.stream().collect(Collectors.toSet());
        Stack stack1 = nums.stream().collect(Collectors.toCollection(Stack::new));
        // 3. String
        String str = nums.stream().collect(Collectors.joining()).toString();
        System.out.println(str);
        System.out.println("清单 10. 留下偶数");
        Integer[] sixNums = {1, 2, 3, 4, 5, 6};
        Integer[] evens =
                Stream.of(sixNums).filter(n -> n % 2 == 0).toArray(Integer[]::new);
        System.out.println(JSON.toJSONString(evens));
    }

    public static void main(String[] args) {
        DemoLambda.getInstance().stream();
    }
}
